<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\ScoreRuleController;
use App\Models\CodeBorrowLog;
use App\Models\CodePlace;
use App\Models\CodeReturnLog;
use App\Models\UserLibraryInfo;
use App\Validate\CodeOnBorrowValidate;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 码上借系统
 */
class CodeOnBorrowController extends CommonController
{

    public $model = null;
    public $validate = null;
    public $score_type = 18;

    public function __construct()
    {
        parent::__construct();

        $this->model = new CodePlace();
        $this->validate = new CodeOnBorrowValidate();
    }
    /**
     * 扫码借，扫描场所码后，获取场所信息，验证场所数据
     * @param lon 经度
     * @param lat 纬度
     * @param qr_code 二维码值
     */
    public function getCodeInfo()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('get_code_info')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        //验证距离
        $codePlaceModel = new CodePlace();
        $checkPlaceCodeDistance = $codePlaceModel->checkPlaceCodeDistance($this->request->qr_code, $this->request->lon, $this->request->lat);
        if ($checkPlaceCodeDistance !== true) {
            return $this->returnApi(201, $checkPlaceCodeDistance);
        }

        //增加行为分析
        $appInviteCodeBehaviorModel = new  \App\Models\AppInviteCodeBehavior();
        $appInviteCodeBehaviorModel->add(19);


        $code_info = $codePlaceModel->getPlaceCodeInfo($this->request->qr_code, ['id', 'name']);
        if ($code_info) {
            return $this->returnApi(200, '获取成功', true, $code_info);
        }
        return $this->returnApi(203, '获取失败,请重新扫码！');
    }

    /**
     * 扫码借书，还书，获取书籍信息
     * @param barcode 条形码
     * @param lon 经度
     * @param lat 纬度
     * @param qr_code 二维码值
     */
    public function getBookInfoByBarcode()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('get_book_info_by_barcode')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        //验证距离
        $codePlaceModel = new CodePlace();
        $checkPlaceCodeDistance = $codePlaceModel->checkPlaceCodeDistance($this->request->qr_code, $this->request->lon, $this->request->lat);
        if ($checkPlaceCodeDistance !== true) {
            return $this->returnApi(201, $checkPlaceCodeDistance);
        }

        //增加行为分析
        $appInviteCodeBehaviorModel = new  \App\Models\AppInviteCodeBehavior();
        $appInviteCodeBehaviorModel->add(19);

        $libApi = $this->getLibApiObj();
        $res = $libApi->getAssetByBarcode($this->request->barcode);
        if ($res['code'] == 200) {
            return $this->returnApi(200, '获取成功', true, $res['content']);
        }
        return $this->returnApi(203, '获取失败,请重新扫码！');
    }
    /**
     * 借阅书籍
     * @param token 用户token，必须绑定读者证
     * @param barcode 条形码
     * @param lon 经度
     * @param lat 纬度
     * @param qr_code 二维码值
     */
    public function borrowBook()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('borrow_book')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //验证距离
        $codePlaceModel = new CodePlace();
        $checkPlaceCodeDistance = $codePlaceModel->checkPlaceCodeDistance($this->request->qr_code, $this->request->lon, $this->request->lat);
        if ($checkPlaceCodeDistance !== true) {
            return $this->returnApi(201, $checkPlaceCodeDistance);
        }

        # 判断读者证是否异常及是否过期
        $user_id = $this->request->user_info['id'];
        $userLibraryInfoModel = new UserLibraryInfo();
        $account_lib_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id);
        if (is_string($account_lib_info)) {
            return $this->returnApi(204, $account_lib_info);
        }
        $account = $account_lib_info['account'];
        $account_id = $account_lib_info['account_id'];


        $libApi = $this->getLibApiObj();
        $res = $libApi->getAssetByBarcode($this->request->barcode);
        if ($res['code'] !== 200) {
            return $this->returnApi(202, "获取书籍信息失败");
        }
        // if ($res['content']['status'] !== 'b') {
        //     return $this->returnApi(202, "此书当前馆藏状态为:" . $res['content']['status_name'] . "，不允许借阅");
        // }

        //验证借阅借阅条件retubook
        $checkBorrowRetuenWhere = $libApi->validateBorrow($this->request->barcode);
        if ($checkBorrowRetuenWhere['code'] != 200) {
            return $this->returnApi(202, $checkBorrowRetuenWhere['msg']);
        }

        //进行书籍借阅
        DB::beginTransaction();
        try {
            //写入本地 
            $codeBorrowLogModel = new CodeBorrowLog();
            $place_code_info = $codePlaceModel->getPlaceCodeInfo($this->request->qr_code);

            $log_id =  $codeBorrowLogModel->addData($res['content'], $user_id, $account, $place_code_info['id']);

            $system_id = $this->systemAdd('扫码借书', $user_id, $account_id, 46, $log_id, '扫码借书成功，书名为：《' . $res['content']['book_name'] . '》');

            //判断积分是否满足条件
            if (config('other.is_need_score') === true) {
                $scoreRuleObj = new ScoreRuleController();
                $score_status = $scoreRuleObj->checkScoreStatus($this->score_type, $user_id, $account_id);
                if ($score_status['code'] == 202 || $score_status['code'] == 203) {
                    throw new Exception($score_status['msg']); //'积分不足无法参加活动'
                } elseif ($score_status['code'] == 200) {
                    $scoreRuleObj->scoreChange($score_status, $user_id, $account_id, $system_id); //添加积分消息
                }
            }

            //写入ilas系统 
            $result = $libApi->bookBorrow($account, $this->request->barcode);
            if ($result['code'] != 200) {
                throw new Exception("ILAS接口存在异常，请联系管理员处理");
            }

            DB::commit();
            return $this->returnApi(200, "借阅成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage() . $e->getFile() . $e->getLine());
        }
    }

    /**
     * 归还书籍
     * @param barcode 条形码
     * @param lon 经度
     * @param lat 纬度
     * @param qr_code 二维码值
     */
    public function returnBook()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('return_book')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //验证距离
        $codePlaceModel = new CodePlace();
        $checkPlaceCodeDistance = $codePlaceModel->checkPlaceCodeDistance($this->request->qr_code, $this->request->lon, $this->request->lat);
        if ($checkPlaceCodeDistance !== true) {
            return $this->returnApi(201, $checkPlaceCodeDistance);
        }

        $user_id = $this->request->user_info['id'];
        $libApi = $this->getLibApiObj();
        $res = $libApi->getAssetByBarcode($this->request->barcode);
        if ($res['code'] !== 200) {
            return $this->returnApi(202, "获取书籍信息失败");
        }

        // if ($res['content']['status'] !== 'c') {
        //     return $this->returnApi(202, "此书当前馆藏状态异常，请联系管理员处理");
        // }

        //验证借阅归还条件
        $account_id = null;
        // $checkBorrowRetuenWhere = $libApi->validateReturn($res['content']['user_info']['reader_id'],  $this->request->barcode, 'retubook');
        // if ($checkBorrowRetuenWhere['code'] != 200) {
        //     return $this->returnApi(202, $checkBorrowRetuenWhere['msg']);
        // }

        //进行书籍借阅
        DB::beginTransaction();
        try {
            //写入本地 
            $codeReturnLogModel = new CodeReturnLog();
            $place_code_info = $codePlaceModel->getPlaceCodeInfo($this->request->qr_code);
            $log_id = $codeReturnLogModel->addData($res['content'], $user_id, $place_code_info['id']);
            //写入ilas系统 
            $result = $libApi->bookReturn($this->request->barcode);
            if ($result['code'] != 200) {
                throw new Exception("ILAS接口存在异常，请联系管理员处理");
            }

            $system_id = $this->systemAdd('扫码还书', $user_id, $account_id, 47, $log_id, '扫码还书成功，书名为：《' . $res['content']['book_name'] . '》');
            DB::commit();
            return $this->returnApi(200, "归还成功", true);
        } catch (\Exception $e) {
            Log::error($e->getMessage() . $e->getFile() . $e->getFile());
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }



    /**
     * 借阅操作列表
     * @param user_id  用户id
     * @param keywords  检索条件
     * @param place_code_id  场所码id
     * @param start_time 开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 结束时间     数据格式    2020-05-12 12:00:00
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function borrowList()
    {
        $user_id = $this->request->user_info['id'];
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $keywords = $this->request->keywords;
        $place_code_id = $this->request->place_code_id;
        $page = intval($this->request->page, 1) ?: 1;
        $limit = intval($this->request->limit, 1) ?: 10;
        $codeBorrowLogModel = new CodeBorrowLog();
        $res = $codeBorrowLogModel->lists($user_id, $place_code_id, $keywords, $start_time, $end_time, $limit);

        if ($res['data']) {
            $res['data'] = $this->disDataSameLevel($res['data'], 'con_code_place', ['name' => 'code_place_name']);

            // $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);
            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }

        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 归还操作列表
     * @param user_id  用户id
     * @param keywords  检索条件
     * @param place_code_id  场所码id
     * @param start_time 开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 结束时间     数据格式    2020-05-12 12:00:00
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function returnList()
    {
        $user_id = $this->request->user_info['id'];
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $keywords = $this->request->keywords;
        $place_code_id = $this->request->place_code_id;
        $page = intval($this->request->page, 1) ?: 1;
        $limit = intval($this->request->limit, 1) ?: 10;

        $codeReturnLogModel = new CodeReturnLog();
        $res = $codeReturnLogModel->lists($user_id, $place_code_id, $keywords, $start_time, $end_time, $limit);

        if ($res['data']) {
            $res['data'] = $this->disDataSameLevel($res['data'], 'con_code_place', ['name' => 'code_place_name']);
            //   $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);
            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }

        return $this->returnApi(203, '暂无数据');
    }
}
